<?php

namespace PhpYes\Modules\Log\Backend;


use PhpYes\Modules\Log\LoggerBackendBase;
use PhpYes\Modules\Log\LogLevel;
use PhpYes\Modules\Log\LogRecordInterface;

class BackendSyslog extends LoggerBackendBase
{
    /**
     * protected 暴露给子类
     * @var array
     */
    protected static $logLevel2SyslogPriority = array(
        LogLevel::EMERGENCY => LOG_EMERG,
        LogLevel::ALERT => LOG_ALERT,
        LogLevel::CRITICAL => LOG_CRIT,
        LogLevel::ERROR => LOG_ERR,
        LogLevel::WARNING => LOG_WARNING,
        LogLevel::NOTICE => LOG_NOTICE,
        LogLevel::INFO => LOG_INFO,
        LogLevel::DEBUG => LOG_DEBUG,
    );

    /**
     * protected 暴露给子类
     * @var bool
     */
    protected static $isOpenlog = false;

    public function __destruct()
    {
        if (self::$isOpenlog) {
            closelog();
            self::$isOpenlog = false;
        }
    }

    /**
     * @param LogRecordInterface $logRecord
     * @return void
     */
    public function logRecord(LogRecordInterface $logRecord)
    {
        if (!self::$isOpenlog) {
            self::$isOpenlog = openlog(false, LOG_ODELAY, LOG_USER);
        }
        if (!self::$isOpenlog) {
            return;
        }

        $level = $logRecord->getLevel();
        $priority = isset(self::$logLevel2SyslogPriority[$level]) ? self::$logLevel2SyslogPriority[$level] : LOG_ERR;
        syslog($priority, $logRecord->getLogMessage());
    }
}